package com.woniuxy.rbac.web.api;

import com.woniuxy.rbac.entity.ResponseResult;
import com.woniuxy.rbac.entity.User;
import com.woniuxy.rbac.service.UserService;
import com.woniuxy.rbac.shiro.SysToken;
import com.woniuxy.rbac.utils.Audience;
import com.woniuxy.rbac.utils.JwtUtil;
import com.woniuxy.rbac.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 用户操作Controller类
 *
 * @Auther: L
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public ResponseResult add(@RequestBody UserVO userVO) {
        SimpleHash simpleHash=new SimpleHash("md5",userVO.getUser().getPassword(),userVO.getUser().getAccount(),1024);
        userVO.getUser().setPassword(simpleHash.toHex());
        userService.add(userVO.getUser(),userVO.getPermIds(),userVO.getRoleIds());
        return ResponseResult.SUCCESS;
    }

    @GetMapping("getall")
    public String getAll(Model model) {
        model.addAttribute("users", userService.getAll());
        return "user/user_list";
    }

    @GetMapping("/del/{id}")
    public String del(@PathVariable int id) {
        userService.delById(id);
        return "redirect:/user/getall"; //前台重定向
    }


    @Autowired
    private Audience audience;

    @PostMapping("/login")
    @ResponseBody
    public ResponseResult login(@RequestBody User user, HttpSession session) {
        SysToken sysToken = new SysToken(user.getAccount(),user.getPassword());

        User user1 = userService.login(user.getAccount());
        Subject subject = SecurityUtils.getSubject();

        try {

            subject.login(sysToken);
            session.setAttribute("user1",subject.getPrincipal());
            String jwt = JwtUtil.createJwt(user1.getId(), user1.getAccount(), audience);
            System.out.println(jwt);
            return new ResponseResult(9000,jwt);
        } catch (UnknownAccountException uae) {
            return new ResponseResult(9001,"账号不存在");
        } catch (IncorrectCredentialsException ice) {
            return new ResponseResult(9002,"密码错误");
        }


    }

    @GetMapping("test")
    @ResponseBody
    public ResponseResult test(@RequestHeader("token") String token) {
        log.debug("token:{}", token);
        //解析出来id或account
        return ResponseResult.SUCCESS;
    }


}
